package com.xcx.utils;

import com.alibaba.fastjson.JSONObject;
import com.xcx.exception.BaseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

@Component
public class SQLUtils {
    @Autowired
    private  RestTemplate restTemplate;


    public  String sendSql(String sql,String method){
        MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        ResponseEntity<String> stringResponseEntity = null;
        formData.add("sql",sql);
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(formData, headers);
        //发送post请求
        stringResponseEntity = restTemplate.postForEntity("http://xxb.zzjdyf.com:41980/springboot/"+method, requestEntity, String.class);
        String body = stringResponseEntity.getBody();
        if (StringUtils.startsWithIgnoreCase(body,"{\"status\": 1")) {
            throw new BaseException("执行失败");
        }
        JSONObject json = JSONObject.parseObject(body);
        String data = json.getString("data");
        return data;
    }

}
